<template>
    <el-dialog v-model="dialogVisible" title="规划建议" width="60%" :append-to-body="true" :close-on-click-modal="false">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="平均年龄" prop="avgAge">
                <el-input-number v-model="form.avgAge" :min="1" :max="100" />
            </el-form-item>

            <el-form-item label="预算" prop="budget">
                <el-input v-model="form.budget" placeholder="请输入预算，例如: 3000元/人" />
            </el-form-item>

            <el-form-item label="出行天数" prop="days">
                <el-input-number v-model="form.days" :min="1" :max="30" />
            </el-form-item>

            <el-form-item label="目的地" prop="destination">
                <el-input v-model="form.destination" :placeholder="getRegionsText()" />
            </el-form-item>

            <el-form-item label="出行人数" prop="numPeople">
                <el-input-number v-model="form.numPeople" :min="1" />
            </el-form-item>

            <!-- 偏好输入框 -->
            <el-form-item label="偏好" prop="preferences">
                <el-input v-model="form.preferences" placeholder="请输入偏好，多个偏好用逗号分隔" />
            </el-form-item>

            <!-- 出行风格输入框 -->
            <el-form-item label="出行风格" prop="travelStyle">
                <el-input v-model="form.travelStyle" placeholder="请输入出行风格，例如: 轻松休闲" />
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="handleCancel" :disabled="loading">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="loading">
                {{ loading ? '正在获取建议...' : '确定' }}
            </el-button>
        </template>
    </el-dialog>
    <el-dialog v-model="resultVisible" title="AI建议" width="60%" :append-to-body="true">
        <div class="suggestion-content">
            <div class="section">
                <h3>总体分析</h3>
                <p>{{ aiMessage.summary }}</p>
            </div>
            <div class="section">
                <h3>旅行建议</h3>
                <p>{{ aiMessage.travel_tips }}</p>
            </div>
            <div class="section">
                <h3>预算分析</h3>
                <p>{{ aiMessage.budget_analysis }}</p>
            </div>
        </div>
    </el-dialog>
</template>

<script setup lang="ts">



import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, type FormInstance } from 'element-plus'
import { getSpotRecommendations } from '@/api/Gpt'
import { useFormStore } from '@/stores/FormStore'

interface AiAnalysis {
    summary: string;
    travel_tips: string;
    budget_analysis: string;
}
interface ApiResponse {
    status: string;
    message: string | null;
    data: {
        spot_details: Array<{
            name: string;
            description: string;
            detailed_analysis: string;
            visiting_tips: string;
            budget_estimation: string;
            recommended_duration: string;
        }>;
        analysis: {
            summary: string;
            travel_tips: string;
            budget_analysis: string;
        };
    };
}



const loading = ref(false)

const props = defineProps<{
    visible: boolean,
    spotIds: number[],
    spots: Array<{
        attractionId: number,
        name: string,
        region?: string // 景点所在地区
    }>
}>()

const emit = defineEmits(['update:visible', 'submit'])

const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
})

const resultVisible = ref(false)

const aiMessage = ref<AiAnalysis>({
    summary: '',
    travel_tips: '',
    budget_analysis: ''
})

const formRef = ref<FormInstance>()
const formStore = useFormStore()

const form = reactive({
    avgAge: null,
    budget: '',
    days: null,
    destination: '',
    numPeople: null,
    preferences: '',
    travelStyle: ''
})

const rules = {
    avgAge: [{ required: true, message: '请输入平均年龄' }],
    days: [{ required: true, message: '请输入出行天数' }],
    // destination: [{ required: true, message: '请输入目的地' }],
    numPeople: [{ required: true, message: '请输入出行人数' }],
    budget: [{ required: true, message: '请输入预算' }],
    preferences: [{ required: true, message: '请输入偏好' }],
    travelStyle: [{ required: true, message: '请输入出行风格' }]
}

// 预填景点名称
const getRegionsText = () => {
    // console.log('当前spots:', props.spots)

    if (!props.spots?.length) return '暂无景点信息'

    // 使用景点名称
    const spotNames = props.spots
        .map(spot => spot.name)
        .filter(name => !!name)

    return spotNames.join('、')
}

const handleCancel = () => {
    dialogVisible.value = false
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        loading.value = true
        // 处理偏好数据 - 将输入的字符串按逗号分隔
        const preferencesString = typeof form.preferences === 'string'
            ? form.preferences
            : String(form.preferences || '')

        const requestData = {
            spotId: props.spotIds,
            travelInfo: {
                avgAge: form.avgAge,
                budget: form.budget,
                days: form.days,
                destination: form.destination,
                numPeople: form.numPeople,
                preferences: preferencesString,
                travelStyle: form.travelStyle
            }
        }
        // 保存表单数据
        formStore.setFormData({
            numPeople: form.numPeople,
            avgAge: form.avgAge,
            destination: form.destination,
            days: form.days,
            travelStyle: form.travelStyle,
            budget: form.budget,
            preferences: preferencesString.split(',').map(p => p.trim())
        })
        emit('submit', requestData)
        dialogVisible.value = false
    } catch (error) {
        ElMessage.error('请填写完整信息')
    } finally {
        loading.value = false
    }
}

// 添加展示结果方法
const showResult = (response: ApiResponse) => {
    console.log('接收到的响应:', response)

    if (!response?.data.analysis) {
        console.error('数据格式错误:', response)
        ElMessage.error('返回数据格式错误')
        return
    }

    try {
        // 更新 aiMessage 的值
        aiMessage.value = {
            summary: response.data.analysis.summary || '暂无总体分析',
            travel_tips: response.data.analysis.travel_tips || '暂无旅行建议',
            budget_analysis: response.data.analysis.budget_analysis || '暂无预算分析'
        }
        resultVisible.value = true
    } catch (error) {
        console.error('处理响应数据错误:', error)
        ElMessage.error('处理返回数据失败')
    }
}

const prefillForm = () => {
    const lastData = formStore.lastFormData
    if (lastData) {
        form.numPeople = lastData.numPeople
        form.avgAge = lastData.avgAge
        form.destination = lastData.destination
        form.days = lastData.days
        form.travelStyle = formStore.mapTravelStyle(lastData.travelStyle, false)
        form.budget = formStore.mapBudget(lastData.budget, false)
        form.preferences = lastData.preferences
    }
}

watch(() => dialogVisible.value, (newVal) => {
    if (newVal) {
        prefillForm()
    }
})

defineExpose({
    showResult: (response: ApiResponse) => {
        console.log('接收到的响应:', response) // 添加调试日志

        if (!response?.data.analysis) {
            console.error('数据格式错误:', response) // 添加错误日志
            ElMessage.error('返回数据格式错误')
            return
        }

        try {
            aiMessage.value = {
                summary: response.data.analysis.summary || '暂无总体分析',
                travel_tips: response.data.analysis.travel_tips || '暂无旅行建议',
                budget_analysis: response.data.analysis.budget_analysis || '暂无预算分析'
            }
            resultVisible.value = true
        } catch (error) {
            console.error('处理响应数据错误:', error)
            ElMessage.error('处理返回数据失败')
        }
    },
    prefillForm
})
</script>

<style scoped>
/* 对话框样式 */
:deep(.el-dialog) {
    margin: 15vh auto !important;
    max-width: 900px;
    min-width: 600px;
}

:deep(.el-dialog__body) {
    max-height: 60vh;
    overflow-y: auto;
    padding: 20px 30px;
}

.suggestion-content {
    white-space: pre-wrap;
    line-height: 1.6;
    font-size: 14px;
    padding: 16px;
}
</style>